import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import css from 'styled-jsx/css';

import Meta from '@/client/components/Meta';
import {getHomeMenus} from '../../models/actions/home';

import globalStyle from './global.css';
import styles from './index.css';

@withRouter
@connect(
    (state, props) => ({
        menus: state.home.menus ? state.home.menus : {}
    }),
    dispatch => ({
        getHomeMenus: bindActionCreators(getHomeMenus, dispatch)
    })
)
export default class Home extends React.Component {

    static propTypes = {
        menus: PropTypes.object.isRequired,

        getHomeMenus: PropTypes.func.isRequired
    }

    constructor () {
        super();
        this.state = {
            curColor: '#ff0000'
        }
        this.onHomeTitleClick =  this.onHomeTitleClick.bind(this);
    }

    componentDidMount() {
        if(JSON.stringify(this.props.menus) === '{}') {
            this.props.getHomeMenus();
        }
    }

    // 变色
    onHomeTitleClick (e) {
        e.preventDefault();
        let red = Math.floor( Math.random() * (255 + 1) ).toString(16);
        let green = Math.floor( Math.random() * (255 + 1) ).toString(16);
        let blue = Math.floor( Math.random() * (255 + 1) ).toString(16);
        this.setState({
            curColor: `#${red}${green}${blue}`
        })
    }

    render () {
        let { menus } = this.props;
        let { curColor } = this.state;
        return (
            <div>
                <Meta title="首页"/>

                <p onClick={this.onHomeTitleClick} className="homeTitle">Home Page One</p>
                {Object.keys(menus).map((n, i) => (
                    <div key={i}>
                        <span>{n}: </span>
                        <span>{menus[n]}</span>
                    </div>
                ))}
                {
                // 样式
                }
                <style jsx global>{ globalStyle }</style>
                <style jsx>{ styles }</style>
                {
                // 动态样式写到这里
                }
                <style jsx>{`
                    p.homeTitle {
                        color: ${ curColor }
                    }
                `}</style>
            </div>
        )
    }
}